package com.viewsky.base.back.config;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.viewsky.base.back.util.Constant;
import com.viewsky.base.back.util.JwtUtil;

import io.jsonwebtoken.Claims;

@Aspect
@Component
public class TokenAspect
{
	@Value("${config.authentication.method}")
	private String strAuthenticationMethod;
	
	@Pointcut("execution(* com.viewsky.base.back.controller.*.*.*(..)) && "
			+ "!execution(* com.viewsky.base.back.controller.user.UserController.*(..))")
  public void pcController()
	{
		
  }
	
	@AfterReturning("pcController()")
	public void addTokenToHeaderIfNeed(JoinPoint jp) throws Throwable
	{
		/* 每次访问请求后，更新header中的token过期时间 */
		if(Constant.AuthenticationMethod.TOKEN.equals(strAuthenticationMethod))
		{
			RequestAttributes ra = RequestContextHolder.getRequestAttributes();
			HttpServletRequest request = ((ServletRequestAttributes)ra).getRequest();	
			HttpServletResponse response = ((ServletRequestAttributes)ra).getResponse();
			
			String strToken = request.getHeader("Authorization");
			strToken = strToken.split("^" + Constant.DEF_TOKEN_HEADER)[1];
			Claims mapClaim = JwtUtil.decodeToken(strToken);
			
			Date expiration = new Date(System.currentTimeMillis() +
					Constant.DEF_TOKEN_EXPIRATION);
			
			strToken = JwtUtil.generateToken(mapClaim, expiration);
			response.addHeader("Authorization", Constant.DEF_TOKEN_HEADER + strToken);
			response.addHeader("Access-Control-Expose-Headers", "Authorization");
			response.addHeader("Cache-Control", "no-store");
		}
	}
}
